package com.iweb.zuul.filters;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.iweb.commons.token.JwtUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class TokenFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    // 过滤器的执行顺序
    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 1;
    }

    // Filter 运行所需要的标准或条件。
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        log.info("鉴权网关拦截");
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        // 获取请求url
        String uri = request.getRequestURI();
        log.info("uri={}", uri);
        // 如果是 登录则放行
        if (validateUri(uri)) return null;
        // 获取token
        String token = request.getHeader("token");
        log.info("token={}", token);
        // 如过没有令牌则返回没有令牌
        if (token == null) {
            log.info("没有令牌");
            Map<String, String> message = new HashMap<>();
            message.put("message", "token令牌为空");
            tokenFalse(context, HttpStatus.UNAUTHORIZED.value(), JSON.toJSONString(message));
            return null;
        }
        // 获取令牌中的信息
        try {
            Claims claims = JwtUtil.parseJWT(token);
            log.info("username={}", claims.getSubject());
        } catch (Exception e) {
            e.printStackTrace();
            // 解析异常
            Map<String, String> message = new HashMap<>();
            message.put("message", e.getMessage());
            tokenFalse(context, HttpStatus.UNAUTHORIZED.value(), JSON.toJSONString(message));
        }
        return null;
    }

    private void tokenFalse(RequestContext context, Integer code, String message) {
        context.setSendZuulResponse(false);
        context.setResponseStatusCode(code);
        context.setResponseBody(message);
        context.getResponse().setContentType(Convert.toStr(MediaType.APPLICATION_JSON_UTF8_VALUE));
    }

    private boolean validateUri(String uri) {
        return "/user/user/login".equals(uri);
    }
}
